package com.demo.web.converter;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;

/**
 * 子定义对象转换
 */
public class MappingFastJson2HttpMessageConverter extends AbstractHttpMessageConverter<Object> {

    private final MediaType supportedMediaType = MediaType.APPLICATION_JSON;
    private final Charset defaultCharset = Charset.forName("utf-8");

    public MappingFastJson2HttpMessageConverter() {
        setSupportedMediaTypes(Collections.singletonList(supportedMediaType));
        setDefaultCharset(defaultCharset);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return JSON.parseObject(StreamUtils.copyToString(inputMessage.getBody(), getDefaultCharset()), clazz);
    }

    @Override
    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        StreamUtils.copy(JSON.toJSONString(o), getDefaultCharset(), outputMessage.getBody());
    }

}
